//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Text.RegularExpressions;
using System.Xml;
using CommunityServer.Components;

namespace CommunityServer.Discussions.Components
{
	/// <summary>
	/// Summary description for CollapseModule.
	/// </summary>
	public class CollapseModule : ICSModule
	{
		public CollapseModule() { }

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PreRenderPost += new CSPostEventHandler(csa_PreRenderPost);
		}

		private void csa_PreRenderPost(IContent content, CSPostEventArgs e)
		{
			if(e.ApplicationType == ApplicationType.Forum)
			{
				ForumPost post = content as ForumPost;
                if(post != null)
                {
                    int number = 1;
                    int indexCut = post.FormattedBody.ToLower().IndexOf("[collapse");

                    string startCollapse = "<div class=\"ForumCollapsedReply\"><input id=\"ReplyExpander$1_tracker\" type=\"hidden\" value=\"True\" />[ <span style=\"cursor: hand\" onclick=\"return ExpanderPanel_Toggle('ReplyHolder$1','','ReplyExpander$1_tracker','','');\" >Click to expand</span> ]</div><div id=\"ReplyHolder$1\" class=\"ForumCollapsedReplyChild\" style=\"display:none;\">";
                    string startCollapseTitle = "<div class=\"ForumCollapsedReply\"><input id=\"ReplyExpander$1_tracker\" type=\"hidden\" value=\"True\" />[ <span style=\"cursor: hand\" onclick=\"return ExpanderPanel_Toggle('ReplyHolder$1','','ReplyExpander$1_tracker','','');\" >$3</span> ]</div><div id=\"ReplyHolder$1\" class=\"ForumCollapsedReplyChild\" style=\"display:none;\">";
                    string endCollapse = "</div>";
                    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;

                    while(indexCut != -1)
                    {
                        post.FormattedBody = post.FormattedBody.Insert(indexCut + 9, " id=\"" + post.PostID + "_" + number + "\"");
                        number++;
                        indexCut = post.FormattedBody.ToLower().IndexOf("[collapse", indexCut + 9);
                    }

                    post.FormattedBody = Regex.Replace(post.FormattedBody, "\\[collapse(?:\\s*)id=\"((\\d+_\\d+)*?)\"(?:\\s*)title=\"((.|\n)*?)\"\\]", startCollapseTitle, options);
                    post.FormattedBody = Regex.Replace(post.FormattedBody, "\\[collapse(?:\\s*)id=\"((\\d+_\\d+)*?)\"\\]", startCollapse, options);
                    post.FormattedBody = Regex.Replace(post.FormattedBody, "\\[/collapse(\\s*)\\]", endCollapse, options);
                }
			}
		}

	}
}
